<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/10
 * Time: 14:53
 */

include "config.php";
include "status.php";

if($_SERVER["REQUEST_METHOD"] != "POST"){

    print_r(json_encode(Status::$r_0));
    return;
}

//1.准备sql语句

$UID = $_POST["u_id"]; // 用户id
$GID = $_POST["gid"];//产品id


$CNAME = $_POST["goodsName"];//产品 名称
$CPRICE = $_POST["price"];//产品价格
$CNUM = $_POST["num"];//产品数量
$CIMG = $_POST["img"];//产品图片
$CTOTAL = $CPRICE * $CNUM;  //产品总金额


$sqlQuery = "SELECT * FROM cart WHERE u_id= ? ;";

$stmt = $conn->prepare($sqlQuery);
$stmt->bind_param("i", $UID);
$stmt->execute();
$queryResult = $stmt->get_result();


$flag = true; //没有找,插入 insert

while($row = $queryResult->fetch_assoc()){
    if($row["g_id"] == $GID){
        $flag = false;//找到了,就做修改 update
        break;
    }
}


if($flag == true){
    //1.2  某某没有购买过,添加一条 新记录
    $sqlInert = "INSERT INTO cart (`c_name`,`c_price`,`c_num`,`c_img`,`c_total`,`u_id`,`g_id`)
VALUES(?,?,?,?,?,?,?)";

    $stmtI = $conn->prepare($sqlInert);
    $stmtI->bind_param("sssssii", $CNAME, $CPRICE, $CNUM, $CIMG, $CTOTAL, $UID, $GID);
    $stmtI->execute();

    if($stmtI->affected_rows >= 1){
        print_r(json_encode(array("msg" => "加入购车成功i", "status" => 1)));
    } else {
        print_r(json_encode(array("msg" => "加入购车失败i", "status" => -1)));
    }

    $stmtI->close();


} else {
    //1.1  查看某某人是否购买,如果购买,数量修改

    $sqlUpdate = "UPDATE cart SET  c_num=c_num+? ,c_total=c_num*c_price WHERE u_id=?  and g_id=?";

    $stmtU = $conn->prepare($sqlUpdate);
    $stmtU->bind_param("iii", $CNUM,$UID,$GID);
    $stmtU->execute();

    if($stmtU->affected_rows >= 1){
        print_r(json_encode(array("msg" => "加入购车成功u", "status" => 1)));
    } else {
        print_r(json_encode(array("msg" => "加入购车失败u", "status" => -1)));
    }
    $stmtU->close();
}

$conn->close();